﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Net;
using System.IO;

namespace SPSIndia.XSLDemo
{
    class XslHelperClass
    {
        
        public string TransformXmlStringToHtml(string XslFileUrl, string xmlToTransform)
        {

            // Store the actual XSL here.
            string xslAsString;

            // Use the XslTransform object to transform the the XML using the XSL.
            XslCompiledTransform xslt2;

            // The transform needs XPathDocuments (or similar).  Use one for the XSL text and the XML text.
            XPathDocument xpdXslString;
            XPathDocument xpdXmlString;

            // Need arguments on the transform call, but it nothing special needed for that.
            XsltArgumentList xsltArgs;

            // Use a helper method to get the text of the XSL file.
            xslAsString = GetXslText(XslFileUrl);

            // Convert the XML and XSL into XPathDocuments
            xpdXslString = new XPathDocument(new StringReader(xslAsString));
            xpdXmlString = new XPathDocument(new StringReader(xmlToTransform));

            // Set up the XslTransform.
            xslt2 = new XslCompiledTransform(true);

            xsltArgs = new XsltArgumentList();

            // Load the XSL itself.
            xslt2.Load(xpdXslString);

            // Transform the results and save into "results2" string builder by way of a StringWriter.
            StringBuilder results2 = new StringBuilder();
            StringWriter sw = new StringWriter(results2);
            xslt2.Transform(xpdXmlString, xsltArgs, sw);

            // Woo hoo!  Got some results finally!
            return results2.ToString();

        } // transform xml string to html

        private string GetXslText(string XslFileUrl)
        {
            WebClient wc = new WebClient();
            StreamReader sr;
            string xslFileContents;

            // Open up the XSL file from its location and store contents into the string variable xslFileContents.
            wc = new WebClient();
            wc.UseDefaultCredentials = true;
            sr = new StreamReader(wc.OpenRead(XslFileUrl));
            xslFileContents = sr.ReadToEnd();
            sr.Close();

            return xslFileContents;

        }

    } // class XslHelperClass

} // SPSIndia.XSLDemo namespace

